package com.len.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author zhuxiaomeng
 * @date 2018/1/5.
 * @email 154040976@qq.com
 */
public class ApplicationContextUtil implements ApplicationContextAware {

  private static ApplicationContext applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      ApplicationContextUtil.applicationContext = applicationContext;
  }

  public static ApplicationContext getApplicationContext() {
      assertApplicationContext();
      return applicationContext;
  }
  @SuppressWarnings("unchecked")
  public static <T> T getBean(String beanName) {
      assertApplicationContext();
      return (T) applicationContext.getBean(beanName);
  }

  public static <T> T getBean(Class<T> tClass) {
      assertApplicationContext();
      return (T) applicationContext.getBean(tClass);
  }

  private static void assertApplicationContext() {
      if (null == ApplicationContextUtil.applicationContext) {
          throw new RuntimeException("applicationContext为空,请检查是否注入ApplicationContextUtil");
      }
  }
}
